<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Image_model extends MY_Model {

    function __construct() {
        parent::__construct("image", "id");
    }

    public function create($tempFileName, $caption = "", $tags = Array()) {

        // validate file exists
        $tempPath = APPPATH . "temp/img/" . $tempFileName;
        if (file_exists($tempPath)) {
            // generate attr
            $uploaded = date("Y-m-d H:i:s");
            $uploaderId = $this->curUserId();
            if ($uploaderId < 0) {
                return $uploaderId;
            }

            $tagString = "";
            $i = 0;
            foreach ($tags as $tag) {
                $tagString .= $tag;
                if ($i < count($tags) - 1) {
                    $tagString .= ",";
                }
                $i++;
            }

            $generatedId = parent::create(Array(
                        "uploader_id" => $uploaderId,
                        "uploaded" => $uploaded,
                        "caption" => $caption,
                        "tags" => $tagString
            ));

            // move image from temp
            try {
                $permPath = APPPATH . "data/img/" . $generatedId;
                rename($tempPath, $permPath);
                if (file_exists($tempPath . "tmb")) {
                    // check thumbnail exist
                    rename($tempPath . "tmb", $permPath . "tmb");
                }
            } catch (Exception $e) {
                parent::delete(Array("id" => $generatedId));
                $generatedId = -1;
            }

            return $generatedId;
        }
        return -1;
    }

    public function updateFile($imgId, $tempFileName) {
        // move image from temp
        try {
            $tempPath = APPPATH . "temp/img/" . $tempFileName;
            $permPath = APPPATH . "data/img/" . $imgId;
            rename($tempPath, $permPath);
            if (file_exists($tempPath . "tmb")) {
                // check thumbnail exist
                rename($tempPath . "tmb", $permPath . "tmb");
            }
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    protected function read($where = Array(), $fetchForeign = false, $depth = 1, $page = -1, $limit = 10) {
        $results = parent::read($where, $fetchForeign, $depth, $page, $limit);

        foreach ($results as $result) {
            $result->src = base_url("application/data/img/" . $result->id);
            $tempPath = APPPATH . "data/img/" . $result->id . "tmb";
            $result->tmb = $result->src . (file_exists($tempPath) ? "tmb" : "" );
        }

        return $results;
    }

}